/*********************************************************
 *********************************************************
 ********************                  *******************
 *************                                ************
 *******                  _oo0oo_                  *******
 ***                     o8888888o                     ***
 *                       88" . "88                       *
 *                       (| -_- |)                       *
 *                       0\  =  /0                       *
 *                     ___/`---'\___                     *
 *                   .' \\|     |// '.                   *
 *                  / \\|||  :  |||// \                  *
 *                 / _||||| -:- |||||- \                 *
 *                |   | \\\  -  /// |   |                *
 *                | \_|  ''\---/''  |_/ |                *
 *                \  .-\__  '-'  ___/-. /                *
 *              ___'. .'  /--.--\  `. .'___              *
 *           ."" '<  `.___\_<|>_/___.' >' "".            *
 *          | | :  `- \`.;`\ _ /`;.`/ - ` : | |          *
 *          \  \ `_.   \_ __\ /__ _/   .-` /  /          *
 *      =====`-.____`.___ \_____/___.-`___.-'=====       *
 *                        `=---='                        *
 *      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~      *
 *********__佛祖保佑__永无BUG__验收通过__钞票多多__*********
 *********************************************************/
package org.jbase.coder.component;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.jbase.GlobalConstants;

/**
 * Project: jbsb_coder <br/>
 * File: CoderBuilder.java <br/>
 * Class: org.jbase.coder.component.CoderBuilder <br/>
 * Description: <描述类的功能>. <br/>
 * Copyright: Copyright (c) 2011 <br/>
 * Company: http://www.yxtsoft.com/ <br/>
 * Makedate: 2016年12月24日 下午1:20:49 <br/>
 * 
 * @author liuzhanhong
 * @version 1.0
 * @since 1.0
 */
public class CoderBuilder {

	private String modelName;
	private String tplPath;
	private List<String> tplList;

	private static String SOURCE_ROOT = GlobalConstants.Real_Path_Root + File.separator + "code_source" + File.separator
			+ "src" + File.separator + "main" + File.separator;

	private static String SOURCE_JAVA = SOURCE_ROOT + "java" + File.separator + "org" + File.separator + "jbase"
			+ File.separator;
	private static String SOURCE_TPL = SOURCE_ROOT + "resources" + File.separator + "templates" + File.separator;
	private static String SOURCE_MD = SOURCE_ROOT + "resources" + File.separator + "sql" + File.separator + "mysql"
			+ File.separator;

	private GroupTemplate gt = null;

	public CoderBuilder(String modelName) {
		this.modelName = modelName;
		setTplPath(null);
		setTplList(null);
		initGT();
	}

	public CoderBuilder(String modelName, String tplPath) {
		this.modelName = modelName;
		setTplPath(tplPath);
		setTplList(null);
		initGT();
	}

	public CoderBuilder(String modelName, List<String> tplList) {
		this.modelName = modelName;
		setTplPath(null);
		setTplList(tplList);
		initGT();
	}

	public CoderBuilder(String modelName, String tplPath, List<String> tplList) {
		this.modelName = modelName;
		setTplPath(tplPath);
		setTplList(tplList);
		initGT();
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param object
	 */
	public void setTplPath(String tpath) {
		if (tpath == null) {
			tpath = this.modelName;
		}
		this.tplPath = tpath;
	}

	public void setTplList(List<String> tlist) {
		if (tlist == null) {
			tlist = loadTplListFromModelName();
		}
		this.tplList = tlist;
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param modelName2
	 */
	private void initGT() {
		Configuration conf = null;
		try {
			conf = Configuration.defaultConfiguration();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		conf.setStatementStart("@");
		conf.setStatementEnd(null);
		gt = new GroupTemplate(new ClasspathResourceLoader("tpl_coder/" + this.tplPath + "/"), conf);
	}

	public void gen(String tablename, String tabledesc, String entityclassname, List<Map<String, Object>> attrs) {
		for (String tplname : tplList) {
			String sourcePath = getSourcePath(tplname, entityclassname);
			String sourceFile = getSourceFile(tplname, entityclassname);
			Map<String, Object> bind = getBindMap(attrs, entityclassname, tablename, modelName, tabledesc);
			genCode(sourcePath, sourceFile, tplname, bind);
		}
	}

	private Map<String, Object> getBindMap(List<Map<String, Object>> tableAttrs, String entityclassname,
			String tablename, String modulename, String tableDesc) {
		Map<String, Object> bind = new HashMap<String, Object>();
		bind.put("tableAttrs", tableAttrs);
		bind.put("entityclassname", entityclassname);
		bind.put("controllername", entityclassname.toLowerCase());
		bind.put("tablename", tablename.toLowerCase());
		bind.put("modulename", modulename.toLowerCase());
		bind.put("tableDesc", tableDesc);
		bind.put("loclassname", entityclassname.substring(0, 1).toLowerCase() + entityclassname.substring(1));

		return bind;
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param tplname
	 * @param entityclassname
	 * @return
	 */
	private String getSourceFile(String tplname, String entityclassname) {
		if (tplname.endsWith(".html.tpl")) {
			return tplname.substring(4, tplname.indexOf(".tpl"));
		} else if (tplname.endsWith(".md.tpl")) {
			return entityclassname + ".md";
		} else {
			String packagename = tplname.substring(4, tplname.indexOf(".tpl"));
			if ("entity".equals(packagename))
				return entityclassname + ".java";
			else
				return entityclassname + packagename.substring(0, 1).toUpperCase() + packagename.substring(1) + ".java";
		}
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param tplname
	 * @param entityclassname
	 * @return
	 */
	private String getSourcePath(String tplname, String entityclassname) {
		if (tplname.endsWith(".html.tpl")) {
			return SOURCE_TPL + modelName + File.separator + entityclassname + File.separator;
		} else if (tplname.endsWith(".md.tpl")) {
			return SOURCE_MD;
		} else {
			String packagename = tplname.substring(4, tplname.indexOf(".tpl"));
			return SOURCE_JAVA + modelName + File.separator + packagename + File.separator;
		}
	}

	public void genCode(String sourcePath, String sourceFile, String tplName, Map<String, Object> bind) {

		Template template = gt.getTemplate(tplName);
		template.binding(bind);
		String code = template.render();

		File f = new File(sourcePath);
		f.mkdirs();
		File target = new File(sourcePath, sourceFile);
		FileWriter writer = null;
		try {
			writer = new FileWriter(target);
			writer.write(code.toString());
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 描述 : <描述函数实现的功能>. <br/>
	 * <p>
	 * 
	 * @param modelName2
	 * @return
	 */
	private List<String> loadTplListFromModelName() {
		List<String> list = new ArrayList<>();
		File file = new File(
				GlobalConstants.Real_Path_Root + File.separator + "tpl_coder" + File.separator + this.tplPath);
		if (file != null && file.isDirectory()) {
			String[] list2 = file.list();
			for (String fname : list2) {
				if (fname.endsWith(".tpl") && fname.startsWith("tpl_"))
					list.add(fname);
			}
		}
		return list;
	}

}
